/**
 * Copyright (c) 2011-2016, James Zhan 詹波 (jfinal@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tianqi.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.generator.MappingKitGenerator;
import com.jfinal.plugin.activerecord.generator.TableMeta;

/**
 * MappingKit 文件生成器
 */
public class DiyMappingKitGenerator extends MappingKitGenerator{
	
	protected String importTemplate =
		"import com.jfinal.plugin.activerecord.ActiveRecordPlugin;%n%n";
	
	protected String mappingMethodContentTemplate =
				"\t\tarp.addMapping(\"%s\", \"%s\", %s.class);%n";
	protected String compositeKeyTemplate =
			"\t\t// Composite Primary Key order: %s%n";
	
	protected String mappingKitPackageName;
	protected String mappingKitOutputDir;
	protected String mappingKitClassName = "_MappingKit";
	
	
	public DiyMappingKitGenerator(String mappingKitPackageName, String mappingKitOutputDir) {
		super(mappingKitPackageName, mappingKitOutputDir);
		this.mappingKitPackageName = mappingKitPackageName;
		this.mappingKitOutputDir = mappingKitOutputDir;
	}
	
	public void setMappingKitOutputDir(String mappingKitOutputDir) {
		if (StrKit.notBlank(mappingKitOutputDir))
			this.mappingKitOutputDir = mappingKitOutputDir;
	}
	
	public void setMappingKitPackageName(String mappingKitPackageName) {
		if (StrKit.notBlank(mappingKitPackageName))
			this.mappingKitPackageName = mappingKitPackageName;
	}
	
	public void setMappingKitClassName(String mappingKitClassName) {
		if (StrKit.notBlank(mappingKitClassName))
			this.mappingKitClassName = StrKit.firstCharToUpperCase(mappingKitClassName);
	}
	
	public void generate(List<TableMeta> tableMetas) {
		System.out.println("Generate MappingKit file ...");
		File f = new File( mappingKitOutputDir + File.separator + mappingKitClassName + ".java");
		
		if(f.exists()==false){
			//文件不存在，新创建
			super.generate(tableMetas);
		}else{
			String source = this.readToBuffer(f).toString();
			String str = genMappingMethod(tableMetas, source);
			System.out.println(str);
				source = source.replace("//222//", str+"\r\n//222//");
				super.writeToFile(new StringBuilder(source).toString());
		}
	}
	
	protected String genMappingMethod(List<TableMeta> tableMetas, String source) {
		StringBuilder ret = new StringBuilder();
		for (TableMeta tableMeta : tableMetas) {
			if(source.contains(tableMeta.name)){
				continue;
			}
			boolean isCompositPrimaryKey = tableMeta.primaryKey.contains(",");
			if (isCompositPrimaryKey)
				ret.append(String.format(compositeKeyTemplate, tableMeta.primaryKey));
			String add = String.format(mappingMethodContentTemplate, tableMeta.name, tableMeta.primaryKey, tableMeta.modelName);
			ret.append(add);
		}
		return ret.toString();
	}
	
	public StringBuffer readToBuffer(File f) {
		StringBuffer buffer = new StringBuffer();
		try {
			InputStream is = new FileInputStream(f);
			String line; // 用来保存每行读取的内容
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			line = reader.readLine(); // 读取第一行
			while (line != null) { // 如果 line 为空说明读完了
			    buffer.append(line); // 将读到的内容添加到 buffer 中
			    buffer.append("\n"); // 添加换行符
			    line = reader.readLine(); // 读取下一行
			}
			reader.close();
			is.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return buffer;
    }

	
}




